package com.product.android.ui.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.flurry.android.FlurryAgent;
import com.nd.android.u.allcommon.R;
import com.product.android.business.FlurryConst;
import com.product.android.utils.LogUtils;

public class SearchBarWidget extends LinearLayout {

	private LinearLayout mSearchCancelLayout;
	private Button mSearchCancelButton;
	private ImageView mSearchRightImageView;
	private Button clearinput;
	private EditText mSearchEditText;
	private InputMethodManager imm;
	private OnSearchListener mOnSearchListener = null;
	private OnStateListener mOnStateListener =null;
	private final int DEFAULTWIDTH=90;

	public interface OnSearchListener {
		public void onSearchChange(String search);

		public void onSearchCancel();
	}
	
	public interface OnStateListener{
		public void OnEditClick();
		public void OnCancel();
		
	}

	public SearchBarWidget(Context context) {
		super(context);
		viewInit(context);
		logicInit();
		imm = (InputMethodManager) mSearchEditText.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(mSearchEditText, 0);
	}

	public SearchBarWidget(Context context, AttributeSet attrs) {
		super(context, attrs);
		viewInit(context);
		logicInit();
		imm = (InputMethodManager) mSearchEditText.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(mSearchEditText, 0);
	}

	/*** 界面初始界面 **/
	private void viewInit(Context context) {
		inflate(context, R.layout.chat_search_bar_layout, this);
		mSearchCancelLayout = (LinearLayout) findViewById(R.id.search_cancel_layout);
		mSearchCancelButton = (Button) findViewById(R.id.search_cancel_button);
		clearinput = (Button) findViewById(R.id.btn_clear_input);
		mSearchRightImageView = (ImageView) findViewById(R.id.search_right);
		mSearchEditText = (EditText) findViewById(R.id.search_text);

	}

	/*** 逻辑初始面 **/
	private void logicInit() {
		if (mSearchCancelButton != null) {
			mSearchCancelButton.setOnClickListener(mSearchCancelClickListener);
		}
		if (null != clearinput) {
			clearinput.setOnClickListener(mSearchCancelClickListener);
		}

		if (mSearchEditText != null) {
			mSearchEditText.setOnTouchListener(mSearchEditTextOnClickListener);
			mSearchEditText.addTextChangedListener(mSearchTextWatcher);
		}
		setTextEditable(false);
	}

	/** 取消键点击事件处理 **/
	private View.OnClickListener mSearchCancelClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int id=v.getId();
            if(id==R.id.btn_clear_input){
            	mSearchEditText.setText("");
            }else{           	
            	if (mSearchCancelLayout != null	&& mSearchCancelLayout.getVisibility() == View.VISIBLE) {
            		setSearchBarState(LAYOUT_STATE_VIEW);
            	}
            	if(imm!=null&&mSearchEditText.getWindowToken()!=null)imm.hideSoftInputFromWindow(mSearchEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);	
            	 mOnSearchListener.onSearchCancel();
            	 

            }
		}
	};

	/** EditText Touch事件处理 **/
	private View.OnTouchListener mSearchEditTextOnClickListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (mSearchCancelLayout != null
					&& mSearchCancelLayout.getVisibility() != View.VISIBLE) {
				FlurryAgent.logEvent(FlurryConst.CHAT_SEARCH);
				setSearchBarState(LAYOUT_STATE_EDIT);

			}
			return false;
		}
	};

	/** 搜索条文字变化监听器 ***/
	private TextWatcher mSearchTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String filter = s.toString();
			if (filter != null && filter.length() > 0) {
				clearinput.setVisibility(View.VISIBLE);
//				mSearchEditText.setSelection(filter.length());
			}else{
				clearinput.setVisibility(View.GONE);
			}
			if (mOnSearchListener != null) {
				mOnSearchListener.onSearchChange(filter);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			
		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	/***
	 * 设置搜索框是否可以编辑
	 * 
	 * @param isEditable
	 */
	public void setTextEditable(boolean isEditable) {
		if (isEditable) {
			mSearchEditText.setFocusableInTouchMode(true);
			mSearchEditText.setFocusable(true);
			mSearchEditText.requestFocus();
		} else {
			mSearchEditText.setFocusableInTouchMode(false);
			mSearchEditText.clearFocus();
			mSearchEditText.setFocusable(false);
		}
	}

	public static final int LAYOUT_STATE_VIEW = 1;
	public static final int LAYOUT_STATE_EDIT = 2;

	/**
	 * 设置搜索条的状态
	 * 
	 * @param state
	 */
	public void setSearchBarState(int state) {
		int width = mSearchCancelLayout.getWidth();
		if (width == 0) {
			mSearchCancelLayout.measure(
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			width = mSearchCancelLayout.getMeasuredWidth();
			if (width == 0)
				width = DEFAULTWIDTH;
		}
		switch (state) {
		case LAYOUT_STATE_VIEW:
			if (mSearchCancelLayout.getVisibility() == View.GONE) {
				return;
			}
			mSearchEditText.setText("");
			mSearchCancelLayout.startAnimation(getButtonTranslateAnimation(
					false, width));
			mSearchRightImageView.startAnimation(getImageTranslateAnimation(
					false, 10));
			setTextEditable(false);
			mSearchCancelLayout.setVisibility(View.GONE);
			if(mOnStateListener != null)
       		    mOnStateListener.OnCancel();
			break;
		case LAYOUT_STATE_EDIT:
			if (mSearchCancelLayout.getVisibility() == View.VISIBLE) {
				return;
			}
			mSearchCancelLayout.startAnimation(getButtonTranslateAnimation(
					true, width));
			mSearchRightImageView.startAnimation(getImageTranslateAnimation(
					true, 10));
			setTextEditable(true);
			mSearchCancelLayout.setVisibility(View.VISIBLE);
			if(mOnStateListener != null)
				mOnStateListener.OnEditClick();
			break;
		default:
			break;
		}
	}

	public void hideInputStatus() {
		if (imm != null && mSearchEditText.getWindowToken() != null)
			imm.hideSoftInputFromWindow(mSearchEditText.getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	public void showInputStatus(){
		if(imm!=null)
			imm.showSoftInput(mSearchEditText, 0);
		
	}

	/*** 取消按鈕位移動畫 **/
	private TranslateAnimation getButtonTranslateAnimation(boolean in,
			int distance) {
		TranslateAnimation animation = null;
		if (in) {
			animation = new TranslateAnimation(distance, 0, 0, 0);
		} else {
			animation = new TranslateAnimation(0, distance, 0, 0);
		}
		animation.setDuration(300);
		animation.setFillAfter(true);
		return animation;
	}

	/*** 背景存图位移动画 **/
	private TranslateAnimation getImageTranslateAnimation(boolean in,
			int distance) {
		TranslateAnimation animation = null;
		if (in) {
			animation = new TranslateAnimation(0, -distance, 0, 0);
		} else {
			animation = new TranslateAnimation(-distance, 0, 0, 0);
		}
		animation.setDuration(300);
		animation.setFillAfter(true);
		return animation;
	}

	public void setOnSearchListener(OnSearchListener listener) {
		if (listener != null) {
			mOnSearchListener = listener;
		}
	}
	
	public void setOnStateListener(OnStateListener listener)
	{
		if (listener != null){
			mOnStateListener= listener;
		}
		
	}
	
	public void clearEditText(){
		if(mSearchEditText!=null){
			mSearchEditText.setText("");
		}
		if (mSearchCancelLayout.getVisibility() != View.GONE) {
			mSearchCancelLayout.setVisibility(View.GONE);
		}
	}

	
	public void stop()
	{
		mSearchEditText.setText("");
		LogUtils.v("test","213123123");
		if (mSearchCancelLayout != null	&& mSearchCancelLayout.getVisibility() == View.VISIBLE) {
    		setSearchBarState(LAYOUT_STATE_VIEW);
    		LogUtils.v("test","222222");
    	}
    	if(imm!=null&&mSearchEditText.getWindowToken()!=null)imm.hideSoftInputFromWindow(mSearchEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);	
    	{
    		LogUtils.v("test","333333");
        	mOnSearchListener.onSearchCancel();
    	}
	}
	
	void onFocusChange(View v, boolean hasFocus)
	{
	         final boolean isFocus=hasFocus;
	        (new android.os.Handler()).postDelayed(new Runnable() {
	            public void run() {
	                    InputMethodManager imm = (InputMethodManager)
	                    getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
	                    if(isFocus)
	                    {
	                    	showInputStatus();
	                    }
 
	            }
	        }, 500);
	}
	
	/**
	 * 
	 * @n<b>函数名称</b>     :setSearchText
	 * @brief   设置搜索关键字给搜索框
	 * @see
	 * @since    Ver 1.1
	 * @param  @param text
	 * @return void
	 * @<b>作者</b>          :  PanYun
	 * @<b>创建时间</b>      :  2014-1-14上午9:46:25
	 */
	public void setSearchText(String text) {
		if (!TextUtils.isEmpty(text)) {
			mSearchCancelLayout.setVisibility(View.VISIBLE);
			mSearchRightImageView.setVisibility(View.VISIBLE);
			mSearchEditText.setText(text);
			mSearchEditText.setSelection(mSearchEditText.getEditableText().length());
			setTextEditable(true);
		}
	}

	public String getSearchText() {
		if (mSearchEditText == null) {
			return "";
		} else {
			return mSearchEditText.getText().toString();
		}
	}

	public boolean isCancelLayoutVisible() {
		return (mSearchCancelLayout.getVisibility() == View.VISIBLE);
	}
	
	public void performClickCancel() {
		if (mSearchCancelButton != null) {
			mSearchCancelButton.performClick();
		}
	}
}
